<?php

namespace Repository;

use Doctrine\ORM\EntityRepository;

class NewsRepository extends EntityRepository {
	public function addNews($data){
		if(empty($data->post('avatar_image'))):
			$img = null;
		else:
			$img = $this->_em->getRepository('\Entity\ShImage')->findOneById($data->post('avatar_image'));
		endif;

		$news = new \Entity\ShNews();
		$img = $this->_em->getRepository('\Entity\ShImage')->findOneBy(array(
			'id' => $data->post('thumb')
		));
		$news->setTitle($data->post('tieu-de'));
		$news->setThumbnail($img);
		$news->setContent($data->post('noi-dung'));
		$news->setSticky($data->post('stick'));
		$news->setActive($data->post('active'));
		$news->setDate(time());

		$this->_em->persist($news);
		$this->_em->flush();

		return true;
	}
	public function get($id){
		$q = $this->_em->getRepository('Entity\ShNews')->findBy($id);
	}
	public function deleteNews($news){
		$data = $this->_em->getRepository('\Entity\ShNews')->findOneById($news);
		$this->_em->remove($data);
		$this->_em->flush();
		return true;
	}
	public function updateNews($data, $news){
		if(empty($data->post('avatar_image'))):
			$img = null;
		else:
			$img = $this->_em->getRepository('\Entity\ShImage')->findOneById($data->post('avatar_image'));
		endif;

		$news->setTitle($data->post('tieu-de'));
		// $news->setThumbnail(null);
		$news->setContent($data->post('noi-dung'));
		$news->setSticky($data->post('stick'));
		$news->setActive($data->post('active'));
		$news->setDate(time());

		$this->_em->persist($news);
		$this->_em->flush();
		return true;
	}
	
	public function backendPaginate($conf){
		$q = $this->_em->getRepository('\Entity\ShNews')->findBy(
			$conf['condition'], $conf['order'], $conf['limit'], $conf['offset']
			);
		return $q;
	}
	public function total_rows($pag){
		$q = $this->_em->createQueryBuilder()
		               ->select('COUNT(n.id)')
		               ->from('Entity\ShNews', 'n');
		return $q->getQuery()->getSingleScalarResult();
	}

}